#include "Windows.h"

LRESULT CALLBACK WinProc_(HWND WindowsHandle, UINT Message, WPARAM wParam, LPARAM lParam)
{
	switch (Message) {
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	}

	return DefWindowProc(WindowsHandle, Message, wParam, lParam);
}

CWindows::CWindows(HINSTANCE hInstance,LPWSTR Name,bool isWindowed)
{
	this->ScreenHeight_		= 640;
	this->ScreenWidth_		= 800;
	this->hInstance_		= hInstance;
	this->IsWindowed_		= isWindowed;
	this->Name_				= Name;
	WNDCLASSEX wcex;
	ZeroMemory(&wcex, sizeof(wcex));

	this->hInstance_	= hInstance;

	wcex.cbSize			= sizeof(WNDCLASSEX);
	wcex.hInstance		= this->hInstance_;
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.hbrBackground	= (HBRUSH)GetStockObject(BLACK_BRUSH);
	wcex.lpfnWndProc	= (WNDPROC)WinProc_;
	wcex.lpszClassName	= Name_;

	RegisterClassEx(&wcex);

	this->hWnd_	= CreateWindow (Name_, Name_,
		IsWindowed_ ? WS_OVERLAPPEDWINDOW : 
		(WS_EX_TOPMOST | WS_VISIBLE | WS_POPUP),
		CW_USEDEFAULT, CW_USEDEFAULT, 
		ScreenWidth_, 
		ScreenHeight_,
		NULL, NULL, 
		this->hInstance_, NULL);

	ShowWindow(hWnd_,SW_SHOWNORMAL);
	UpdateWindow(hWnd_);
}


CWindows::~CWindows(void)
{
}

void CWindows::initializeWindows()
{
	d3d_ = Direct3DCreate9(D3D_SDK_VERSION);
	D3DPRESENT_PARAMETERS d3dpp; 

	ZeroMemory( &d3dpp, sizeof(d3dpp) );

	d3dpp.Windowed = IsWindowed_?TRUE:FALSE;

	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;

	d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; 
	d3dpp.BackBufferCount = 1;
	d3dpp.BackBufferHeight = ScreenHeight_;
	d3dpp.BackBufferWidth = ScreenWidth_;

	if(FAILED(d3d_->CreateDevice(
			D3DADAPTER_DEFAULT,
			D3DDEVTYPE_HAL,
			hWnd_,
			D3DCREATE_SOFTWARE_VERTEXPROCESSING,
			&d3dpp,
			&d3dDevice_)))
			return;

	D3DXCreateSprite(d3dDevice_, &spriteHandler_);
}

bool CWindows::startDraw()
{
	if (d3dDevice_ == 0) {
		return false;
	}
	else {
		d3dDevice_->Clear(0, 0, D3DCLEAR_TARGET, 0xFF000000, 1.0f, 0);
		d3dDevice_->BeginScene();
		spriteHandler_->Begin(D3DXSPRITE_ALPHABLEND);
		return true;
	}
}

bool CWindows::stopDraw()
{
	spriteHandler_->End();
	d3dDevice_->EndScene();
	d3dDevice_->Present(0, 0, 0, 0);
	return true;
}